package com.easylinkin.linkappapi.machinery.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.machinery.dto.MachineryUserTypeDTO;
import com.easylinkin.linkappapi.machinery.entity.MachineryType;
import com.easylinkin.linkappapi.machinery.entity.MachineryUserLink;
import com.easylinkin.linkappapi.machinery.entity.MachineryUserType;
import com.easylinkin.linkappapi.machinery.mapper.MachineryTypeMapper;
import com.easylinkin.linkappapi.machinery.mapper.MachineryUserLinkMapper;
import com.easylinkin.linkappapi.machinery.mapper.MachineryUserTypeMapper;
import com.easylinkin.linkappapi.machinery.service.MachineryUserTypeService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 人员类别表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class MachineryUserTypeServiceImpl extends
    ServiceImpl<MachineryUserTypeMapper, MachineryUserType> implements MachineryUserTypeService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Autowired
  private MachineryTypeMapper machineryTypeMapper;

  @Autowired
  private MachineryUserLinkMapper machineryUserLinkMapper;

  /**
   * 增加
   * @param machineryUserType
   */
  @Override
  public void insert(MachineryUserType machineryUserType) {
    /**
     * 验证重复
     */
    this.checkExist(machineryUserType);
    //设置基本属性
    this.setBase(machineryUserType);
    this.save(machineryUserType);
  }

  /**
   * 根据id编辑
   * @param machineryUserType
   */
  @Override
  public void updateOne(MachineryUserType machineryUserType) {
    /**
     * 验证重复
     */
    this.checkExist(machineryUserType);
    //设置基本属性
    this.setBase(machineryUserType);
    this.updateById(machineryUserType);
  }

  /**
   * 查询可添加的设备类型
   */
  @Override
  public List<MachineryType> queryTypeList(MachineryType machineryType) {
    QueryWrapper<MachineryType> queryWrapper = new QueryWrapper<>();
    if (StringUtils.isNotBlank(machineryType.getName())){
      queryWrapper.like("name_",machineryType.getName());
    }
    //此时传过来的id为人员类别id
    if (null != machineryType.getId()){
      MachineryUserType machineryUserType = baseMapper.selectById(machineryType.getId());
      String devices = machineryUserType.getDevices();
      if (StringUtils.isNotBlank(devices)){
        String[] strings = devices.split(",");
        queryWrapper.notIn("code_", Arrays.asList(strings));
      }
    }
    List<MachineryType> machineryTypes = machineryTypeMapper.selectList(queryWrapper);
    return machineryTypes;
  }

  /**
   * @Description: 增加设备类别
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void insertDevices(MachineryUserTypeDTO machineryUserTypeDTO) {
    String deviceStr = null;
    Set<String> codes = machineryUserTypeDTO.getMachineryTypes().stream()
        .map(m -> m.getCode()).collect(Collectors.toSet());
    //查询原来的
    MachineryUserType machineryUserType = baseMapper.selectById(machineryUserTypeDTO.getId());
    String devices = machineryUserType.getDevices();
    if (StringUtils.isNotBlank(devices)){
      deviceStr = devices + (","+StringUtils.join(codes,","));
    }else {
      deviceStr = StringUtils.join(codes,",");
    }
    //更新
    UpdateWrapper<MachineryUserType> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id",machineryUserTypeDTO.getId())
        .set("devices_",deviceStr);
    baseMapper.update(null,updateWrapper);
  }

  /**
   * @Description: 删除人员类别（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void delBatch(Set<Integer> ids) {
    ids.forEach(id ->{
      //关联删除人员
      UpdateWrapper<MachineryUserLink> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("type_id_",id);
      machineryUserLinkMapper.delete(updateWrapper);
      baseMapper.deleteById(id);
    });
  }

  /**
   * @Description: 删除设备类别
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void deleteDevices(MachineryUserType machineryUserType) {
    //查询原来的
    MachineryUserType userType = baseMapper.selectById(machineryUserType.getId());
    String devices = userType.getDevices();
    List<String> deviceList = new ArrayList<>(Arrays.asList(devices.split(",")));
    deviceList.remove(machineryUserType.getDevices());
    UpdateWrapper<MachineryUserType> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id",machineryUserType.getId())
        .set("devices_",StringUtils.join(deviceList,","));
    baseMapper.update(null,updateWrapper);
  }

  /**
   * @Description: 根据id查询人员类别详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public MachineryUserTypeDTO findById(Integer id) {
    MachineryUserType machineryUserType = baseMapper.selectById(id);
    MachineryUserTypeDTO machineryUserTypeDTO = BeanUtil
        .toBean(machineryUserType, MachineryUserTypeDTO.class);
    String devices = machineryUserType.getDevices();
    if (StringUtils.isNotBlank(devices)){
      QueryWrapper<MachineryType> queryWrapper = new QueryWrapper<>();
      queryWrapper.in("code_",Arrays.asList(devices.split(",")));
      List<MachineryType> machineryTypes = machineryTypeMapper.selectList(queryWrapper);
      machineryUserTypeDTO.setMachineryTypes(machineryTypes);
    }
    return machineryUserTypeDTO;
  }

  /**
   * @Description: 根据条件，查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public List<MachineryUserTypeDTO> queryList(MachineryUserType machineryUserType) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    machineryUserType.setTenantId(tenantId);
    List<MachineryUserType> machineryUserTypes = baseMapper.findList(machineryUserType);
    List<MachineryUserTypeDTO> machineryUserTypeDTOS = BeanUtil
        .copyToList(machineryUserTypes, MachineryUserTypeDTO.class);
    //查询关联人员数量
    QueryWrapper<MachineryUserLink> linkQueryWrapper = new QueryWrapper<>();
    linkQueryWrapper.eq("tenant_id_", tenantId);
    List<MachineryUserLink> userLinks = machineryUserLinkMapper
        .selectList(linkQueryWrapper);
    machineryUserTypeDTOS.forEach(m->{
      long count = userLinks.stream().filter(u -> m.getId().equals(u.getTypeId())).count();
      m.setCount((int)count);
      //处理name
      if (Integer.valueOf(1).equals(m.getType())){
        String name = m.getName();
        m.setName(name.substring(name.lastIndexOf("/")+1));
      }
    });
    return machineryUserTypeDTOS;
  }

  /**
   * 验证重复
   */
  private void checkExist(MachineryUserType machineryUserType) {
    QueryWrapper<MachineryUserType> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("name_",machineryUserType.getName())
        .eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId());
    //编辑的时候存在id
    Optional.ofNullable(machineryUserType.getId()).ifPresent(id -> queryWrapper.ne("id",machineryUserType.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该人员类别已存在");
    }
  }

  /**
   * 设置基本属性
   * @param machineryUserType
   */
  private void setBase(MachineryUserType machineryUserType) {
    machineryUserType.setModifyTime(new Date());
    machineryUserType.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == machineryUserType.getId()){
      machineryUserType.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      machineryUserType.setCreateTime(new Date());
      machineryUserType.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
  }
}
